function [ data ] = WinsorizeData(data , alpha, replace_option)

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% alpha is the winsorization level. For example a 90% winsorization would 
% see all data below the 5th percentile set to the 5th percentile, and 
% data above the 95th percentile set to the 95th percentile.

% replace_option = 0 , replace extreme observations with NaN
% replace_option = 1 , replace extreme observations with the min/max quantiles
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%


[row_num, column_num] = size(data);

alpha_input = (1-alpha)/2;

% winsorizing data - column by column
data_min = quantile(data,alpha_input,1);
data_max = quantile(data,1-alpha_input,1);

if replace_option == 0
    
    for i = 1:column_num
        temp = data(:,i);
        temp(temp < data_min(i)) = NaN;
        temp(temp > data_max(i)) = NaN;
        data(:,i) = temp;
    end
    
elseif replace_option == 1
    
    for i = 1:column_num
        temp = data(:,i);
        temp(temp < data_min(i)) = data_min(i);
        temp(temp > data_max(i)) = data_max(i);
        data(:,i) = temp;
    end
    
end

data = reshape(data,row_num,column_num);

end
